﻿using Furion.DatabaseAccessor;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using iWare.Wms.Core;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Linq.Dynamic.Core;

namespace iWare.Wms.Application
{
    /// <summary>
    /// 审核供应商服务
    /// </summary>
    [Route("api/ExamineFlower")]
    [ApiDescriptionSettings("供应商模块", Name = "ExamineFlower", Order = 100)]

    public class ExamineFlowerService : IDynamicApiController, ITransient
    {
        private readonly IRepository<SysUser, MasterDbContextLocator> _sysUserRep; //用户仓储
        private readonly IRepository<GoodsDelivery, MasterDbContextLocator> _goodsDeliveryRep; //送货单仓储
        private readonly IRepository<QualityFeedbackDetails, MasterDbContextLocator> _qualityFeedbackDetailsRep; //质检反馈仓储
        private readonly IRepository<SupplierExamineFlower, MasterDbContextLocator> _supplierExamineFlowerRep; //送货单审核记录仓储

        #region 默认
        /// <summary>
        /// 默认
        /// </summary>
        /// <param name="sysUserRep"></param>
        /// <param name="goodsDeliveryRep"></param>
        /// <param name="qualityFeedbackDetailsRep"></param>
        /// <param name="supplierExamineFlowerRep"></param>
        public ExamineFlowerService(
            IRepository<SysUser, MasterDbContextLocator> sysUserRep,
            IRepository<GoodsDelivery, MasterDbContextLocator> goodsDeliveryRep,
            IRepository<QualityFeedbackDetails, MasterDbContextLocator> qualityFeedbackDetailsRep,
            IRepository<SupplierExamineFlower, MasterDbContextLocator> supplierExamineFlowerRep
        )
        {
            _sysUserRep = sysUserRep;
            _goodsDeliveryRep = goodsDeliveryRep;
            _qualityFeedbackDetailsRep = qualityFeedbackDetailsRep;
            _supplierExamineFlowerRep = supplierExamineFlowerRep;
        }
        #endregion

        /// <summary>
        /// 供应商审核通知提醒
        /// </summary>
        /// <returns></returns>
        [HttpGet("MessageReminder")]
        public async Task<MessageReminderOutput> MessageReminder()
        {
            var userId = CurrentUserInfo.UserId;

            var usermodel = await _sysUserRep.FirstOrDefaultAsync(n => n.Id == userId);
            List<MessageReminderList> supplierExamineFlowerOutputs = new List<MessageReminderList>();
            if (usermodel.AdminType == AdminType.SuperAdmin || usermodel.AdminType == AdminType.Admin)
            {
                supplierExamineFlowerOutputs = (from p in _supplierExamineFlowerRep.AsQueryable()
                                                join d in _goodsDeliveryRep.AsQueryable() on p.DeliveryID equals d.Id
                                                where p.UpdatedUserId == null && (p.Status == AuditStatusEnum.yuyuechenggong || p.Status == AuditStatusEnum.shenhezhong)
                                                select new MessageReminderList
                                                {
                                                    ProjectCode = d.ProjectCode,
                                                    DeliveryOrderNo = d.DeliveryNo,
                                                    DeliveryID = d.Id,
                                                    Remarks = d.DeliveryNo + p.Remarks,
                                                    Id = p.Id,
                                                    Status = p.Status
                                                }).ToList();
            }

            if (usermodel.AdminType == AdminType.Supplier)
            {
                var DeliveryIdList = await _supplierExamineFlowerRep.DetachedEntities
                    .Where(p => p.UpdatedUserId == null && p.CreatedUserId == userId)
                    .Select(p => p.DeliveryID).ToListAsync();
                supplierExamineFlowerOutputs = (from p in _supplierExamineFlowerRep.AsQueryable()
                                                join d in _goodsDeliveryRep.AsQueryable() on p.DeliveryID equals d.Id
                                                where p.UpdatedUserId == null && DeliveryIdList.Contains(p.DeliveryID) && p.CreatedUserId != userId
                                                select new MessageReminderList
                                                {
                                                    ProjectCode = d.ProjectCode,
                                                    DeliveryOrderNo = d.DeliveryNo,
                                                    DeliveryID = d.Id,
                                                    Remarks = d.DeliveryNo + p.Remarks,
                                                    Id = p.Id,
                                                    Status = p.Status
                                                }).ToList();
            }

            MessageReminderOutput messageReminderOutput = new MessageReminderOutput();
            messageReminderOutput.AdminTypeName = usermodel.AdminType;
            messageReminderOutput.Count = supplierExamineFlowerOutputs.Count;
            messageReminderOutput.List = supplierExamineFlowerOutputs;
            return messageReminderOutput;
        }

        /// <summary>
        /// 供应商审核通知读取
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("ReadMessage")]
        public async Task ReadMessage(ReadMessageInout input)
        {
            if (input == null || input.IdList == null || input.IdList.Count == 0) throw Oops.Oh(ErrorCode.D4008);

            foreach (var item in input.IdList)
            {
                var supplierExamineFlower = await _supplierExamineFlowerRep
                    .FirstOrDefaultAsync(u => u.Id == item);
                await _supplierExamineFlowerRep.UpdateAsync(supplierExamineFlower, ignoreNullValues: true);
            }
        }

        /// <summary>
        /// 收货质检通知提醒
        /// </summary>
        [HttpGet("CollectNoticeRemind")]
        public async Task<CollectNoticeRemindOutput> CollectNoticeRemind()
        {
            var userId = CurrentUserInfo.UserId;
            var usermodel = await _sysUserRep.FirstOrDefaultAsync(n => n.Id == userId);

            var messageList = new List<string>();
            if (usermodel.AdminType == AdminType.SuperAdmin) return null;
            if (usermodel.AdminType == AdminType.Admin)
            {
                var qualityFeedbackDetails = await _qualityFeedbackDetailsRep.DetachedEntities.Where(z => z.IsAdminRead == YesOrNot.N).ToListAsync();
                foreach (var item in qualityFeedbackDetails)
                {
                    messageList.Add(item.Id + "," + item.DeliveryNo);
                }

                CollectNoticeRemindOutput collectNoticeRemind = new CollectNoticeRemindOutput();
                collectNoticeRemind.Count = messageList.Count;
                collectNoticeRemind.Messages = messageList;
                return collectNoticeRemind;
            }
            else
            {
                var status = new List<int> { 2, 3, 6 };

                var qualityFeedbackDetails = await _qualityFeedbackDetailsRep.DetachedEntities.Where(z => z.SupperCode == usermodel.Account
                && status.Contains((int)z.QualityResult) && z.IsSupperRead == YesOrNot.N).ToListAsync();
                foreach (var item in qualityFeedbackDetails)
                {
                    messageList.Add(item.Id + "," + item.DeliveryNo);
                }

                CollectNoticeRemindOutput collectNoticeRemind = new CollectNoticeRemindOutput();
                collectNoticeRemind.Count = messageList.Count;
                collectNoticeRemind.Messages = messageList;
                return collectNoticeRemind;
            }
        }

        /// <summary>
        /// 收货质检通知读取
        /// </summary>
        [HttpPost("CollectNoticeRead")]
        public async Task CollectNoticeRead([FromBody] CollectNoticeReadInput input)
        {
            if (input == null || input.IdList == null || input.IdList.Count == 0) throw Oops.Oh(ErrorCode.D4008);

            var userId = CurrentUserInfo.UserId;
            var usermodel = await _sysUserRep.FirstOrDefaultAsync(n => n.Id == userId);

            foreach (var item in input.IdList)
            {
                if (usermodel.AdminType == AdminType.Admin)
                {
                    var qualityFeedbackDetails = await _qualityFeedbackDetailsRep.DetachedEntities
                     .FirstOrDefaultAsync(z => z.Id == item);
                    qualityFeedbackDetails.IsAdminRead = YesOrNot.Y;
                    qualityFeedbackDetails.UpdatedTime = DateTimeOffset.Now;
                    await _qualityFeedbackDetailsRep.UpdateAsync(qualityFeedbackDetails);
                }
                else
                {
                    var qualityFeedbackDetails = await _qualityFeedbackDetailsRep.DetachedEntities
                     .FirstOrDefaultAsync(z => z.Id == item);
                    qualityFeedbackDetails.IsSupperRead = YesOrNot.Y;
                    qualityFeedbackDetails.UpdatedTime = DateTimeOffset.Now;
                    await _qualityFeedbackDetailsRep.UpdateAsync(qualityFeedbackDetails);
                }
            }
        }
    }
}
